<template>
    <div style="padding:20px">
        <el-button type="success" @click="showingImportUserDialog">导入用户</el-button>
        <el-button type="success">批量导入用户</el-button>
        <el-button type="primary" @click="exportUserXlsx" :disabled="this.selectedUser.length == 0">导出用户</el-button>
        <el-button type="danger" @click="deleteUser" :disabled="this.selectedUser.length == 0">删除用户</el-button>
    </div>
    <div>
        <el-table :data="userTableData" @selection-change="userTableSeletionChange($event)"
            style="width: 100%; margin-bottom: 20px;height:700px" row-key="id" border default-expand-all>
            <el-table-column type="selection" prop="userId" label="Id" sortable="" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="nickname" label="昵称" />
            <el-table-column prop="sex" :filters="filterClass.sexFilter" label="性别" />
            <el-table-column prop="createdDateFormatted" label="注册时间" sortable />
            <el-table-column prop="areaFormatted" label="所在地区" />
            <el-table-column prop="role" label="身份" :filters="filterClass.roleFilter" />
            <el-table-column prop="number" label="手机号" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column>
                <template #header>
                    <el-input v-model="searchUsername" size="small" placeholder="搜索用户" />
                </template>
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-popconfirm title="确定要删除此用户吗？" @confirm="deleteUser(scope.row)">
                        <template #reference>
                            <el-button size="small" type="danger">删除</el-button>
                        </template>
                    </el-popconfirm>
                    <!-- <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
                </template>
            </el-table-column>
        </el-table>
    </div>
    <el-pagination style="display:flex;justify-content: center;" background layout="prev, pager, next"
        :hide-on-single-page="false" :page-count="pages" :page-size="pageSize" />

    <el-dialog v-model="showUserInfoDialog" :title="importingFlag ? '添加用户' : '修改用户'" :width="500">
        <el-form :model="userInfoForm">
            <el-form-item label="用户Id" v-show="!importingFlag">
                <el-input type="text" disabled v-model="userInfoForm.userId" />
            </el-form-item>
            <el-form-item label="用户名">
                <el-input type="text" autocomplete="off" v-model="userInfoForm.username" />
            </el-form-item>
            <el-form-item label="昵称">
                <el-input type="text" autocomplete="off" v-model="userInfoForm.nickname" />
            </el-form-item>
            <el-form-item label="密码" v-show="importingFlag">
                <el-input type="text" autocomplete="off" v-model="userInfoForm.password" />
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="userInfoForm.sex" size="large">
                    <el-radio label="保密" name="保密">保密</el-radio>
                    <el-radio label="女" name="女">女</el-radio>
                    <el-radio label="男" name="男">男</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="所在班级" style="width:100%">
                <el-autocomplete style="width:100%" v-model="searchGroup.groupName" :fetch-suggestions="queryGroupAsync"
                    placeholder="输入班级名称自动搜索" @select="groupHandleSelect" />
            </el-form-item>
            <el-form-item label="身份">
                <el-radio-group v-model="userInfoForm.role" size="large">
                    <el-radio label="学生" name="学生">学生</el-radio>
                    <el-radio label="老师" name="老师">老师</el-radio>
                    <el-radio label="分站管理员" name="分站管理员" v-if="userInfoForm.role == '分站管理员'">分站管理员</el-radio>
                    <el-radio label="总站管理员" name="总站管理员" v-else-if="userInfoForm.role == '总站管理员'">总站管理员</el-radio>
                    <el-radio label="总站管理员" :name="this.$store.state.user.role" v-else>管理员</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="状态">
                <el-radio-group v-model="userInfoForm.status" size="large">
                    <el-radio label="正常" name="正常">正常</el-radio>
                    <el-radio label="禁用" name="禁用">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号">
                <el-input type="text" autocomplete="off" v-model="userInfoForm.number" />
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input type="email" autocomplete="off" v-model="userInfoForm.email" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <!-- <el-button @click="test">获取</el-button> -->
                <el-button @click="showUserInfoDialog = false">取消</el-button>
                <el-button type="primary" v-show="!importingFlag" @click="updateUser">
                    修改
                </el-button>
                <el-button type="success" v-show="importingFlag" @click="addOneUser">
                    导入
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script>
import xlsx from 'xlsx';
export default {
    data() {
        return {
            filterClass: {
                sexFilter: [
                    {
                        text: '保密', value: '保密'
                    },
                    {
                        text: '女', value: '女'
                    },
                    {
                        text: '男', value: '男'
                    }
                ],
                roleFilter: [
                    {
                        text: '学生', value: '学生'
                    },
                    {
                        text: '老师', value: '老师'
                    },
                    {
                        text: '管理员', value: '管理员'
                    }
                ]
            },
            userInfoForm: {},
            searchUsername: '',
            showUserInfoDialog: false,
            userTableData: [],
            selectedUser: [],
            searchGroup: { groupName: '' },
            importingFlag: false,
            pages: 1,
            current: 1,
            pageSize: 100
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        handleEdit(userRow) {
            this.importingFlag = false
            this.showUserInfoDialog = true
            this.userInfoForm = userRow
            if(this.userInfoForm.group!=null)this.searchGroup=this.userInfoForm.group
            else this.searchGroup={ groupName: '' }
        },
        showingImportUserDialog() {
            this.userInfoForm = {}
            this.importingFlag = true
            this.showUserInfoDialog = true
        },
        groupHandleSelect(selectGroup) {
            this.userInfoForm.groupId = selectGroup.link.groupId
        },
        queryGroupAsync(groupName, callback) {
            if (groupName == null || groupName == '') return
            this.$request.get('/group/group_search?groupName=' + groupName + '&collegeId='
                + this.$store.state.user.collegeId).then(data => {
                    if (data.data.length == 0) {
                        this.$ElMessage({
                            message: '没有找到这个班级',
                            type: 'error',
                        })
                    }
                    let groupList = data.data
                    let groupArray = []
                    groupList.forEach(group => {
                        groupArray.push({ value: group.groupName + ' ( ' + group.leader.nickname + ' ) ', link: group })
                    })
                    callback(groupArray)
                })
        },
        exportUserXlsx() {
            if (this.selectedUser.length == 0) return
            let header = ['id', '用户名', '昵称', '性别', '注册时间', '所在地区', '身份', '手机号', '邮箱']
            let rawHeader = ['userId', 'username', 'nickname', 'sex', 'createdDateFormatted', 'areaFormatted', 'role', 'number', 'email']
            let userSheetWork = []
            this.selectedUser.forEach(user => {
                let userRow = {}
                let userProperIndex = 0
                header.forEach(headerItem => {
                    userRow[headerItem] = user[rawHeader[userProperIndex]]
                    userProperIndex++
                })
                userSheetWork.push(userRow)
            })
            let workBook = xlsx.utils.book_new()
            let workSheet = xlsx.utils.json_to_sheet(userSheetWork)
            xlsx.utils.book_append_sheet(workBook, workSheet)
            xlsx.writeFile(workBook, `导出的用户列表.xlsx`, {
                bookType: 'xlsx'
            })
        },
        addOneUser() {
            let adminBelong = this.$store.state.user.belong.split(',')
            let belong = adminBelong[0] + ',' + adminBelong[1] + ',' + adminBelong[2] + ','+this.userInfoForm.groupId
            this.userInfoForm.belong = belong
            this.addUser([this.userInfoForm])
        },
        addUser(userList) {
            this.$request.post('/admin/user/add_user', JSON.stringify(userList)).then(resp => {
                this.getUserList()
                this.$ElMessage({
                    message: resp.success ? '操作成功' : '操作失败',
                    type: resp.success ? 'success' : 'error',
                })
                if (resp.success) this.showUserInfoDialog = false
            })
        },
        deleteUser(user) {
            let userIds = []
            if (user == null) {
                if (this.selectedUser.length == 0) return
                this.selectedUser.forEach(user => {
                    userIds.push(user.userId)
                })
            } else {
                userIds.push(user.userId)
            }
            this.$request.post('/admin/user/del_user', JSON.stringify(userIds)).then(resp => {
                this.$ElMessage({
                    message: resp.success ? '删除成功' : '删除失败',
                    type: resp.success ? 'success' : 'error',
                })
                this.getUserList()
            })
        },
        updateUser() {
            this.$request.post('/admin/user/update_user', JSON.stringify(this.userInfoForm)).then(resp => {
                this.$ElMessage({
                    message: resp.success ? '修改成功' : '修改失败',
                    type: resp.success ? 'success' : 'error',
                })
                this.getUserList()
                if (resp.success) this.showUserInfoDialog = false
            })
        },
        getUserList() {
            this.$request.get('/admin/user_list?page=' + this.current + '&pageSize=' + this.pageSize).then(data => {
                this.userTableData = data.data.data
                this.pages = data.data.pages
                this.current = data.data.current
            })
        },
        userTableSeletionChange(userList) {
            this.selectedUser = userList
        }
    }
}
</script>

<style scoped>

</style>